package com.cjkj.user.controller;

import com.cjkj.common.core.domain.AjaxResult;
import com.cjkj.common.utils.RedisUtil;
import com.cjkj.common.utils.StringUtils;
import com.cjkj.common.utils.uuid.IdUtils;
import com.cjkj.user.domain.UserInfo;
import com.cjkj.user.domain.dto.CodeRequest;
import com.cjkj.user.domain.dto.WeiChatUserRequest;
import com.cjkj.user.service.IUserInfoService;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

import static com.cjkj.common.utils.HttpSMS.getSendSMS;

@RestController
@RequestMapping("/api/account")
public class AccountController {

    @Resource
    private IUserInfoService userInfoService;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取验证码
     * @param codeRequest
     * @return
     * @throws DocumentException
     */
    @PostMapping("/getCode")
    public AjaxResult getCode(@Valid @RequestBody CodeRequest codeRequest) throws DocumentException {
        if ("reg".equals(codeRequest.getType())) {
            if (userInfoService.phoneHasRegistered(codeRequest.getPhone())) {
                return AjaxResult.error("该账号已注册！");
            }
        } else if ("login".equals(codeRequest.getType())) {
            if (! userInfoService.phoneHasRegistered(codeRequest.getPhone())) {
                return AjaxResult.error("该账号未注册！");
            }
        }

        //这里生成六位随机数
        Integer code = (int) ((Math.random() * 9 + 1) * 100000);
        String rq = getSendSMS(codeRequest.getPhone(), code);
        Document doc = DocumentHelper.parseText(rq);
        Element rootElement = doc.getRootElement();
        Element element = rootElement.element("returnstatus");
        Element elementMsg = rootElement.element("message");
        if ("Success".equals(element.getText())) {
            String codeId = IdUtils.simpleUUID();
            //将验证码保存到Redis中
            String setStatus = redisUtil.setex("sms_code:" + codeId, 300, String.valueOf(code));
            if(StringUtils.isNotBlank(setStatus) && setStatus.equalsIgnoreCase("OK")) {
                return AjaxResult.success("success", codeId);
            } else {
                return AjaxResult.error(setStatus);
            }
        } else {
            return AjaxResult.error(elementMsg.getText());
        }
    }

    /**
     * 用户注册
     * @param weiChatUserRequest
     * @param sessionId
     * @return
     */
    @PostMapping("/register")
    public AjaxResult register(@Valid @RequestBody WeiChatUserRequest weiChatUserRequest, @RequestHeader(value = "SESSIONID") String sessionId) {
        String code = redisUtil.get("sms_code:" + sessionId);
        if (StringUtils.isBlank(code)) {
            return AjaxResult.error("验证码已失效！");
        }
        if (!weiChatUserRequest.getCode().equals(code)) {
            return AjaxResult.error("验证码错误！");
        }
        if (userInfoService.phoneHasRegistered(weiChatUserRequest.getPhone())) {
            return AjaxResult.error("该用户已经注册！");
        }

        UserInfo user = new UserInfo();
        user.setPhone(weiChatUserRequest.getPhone());
        user.setPassword(DigestUtils.md5DigestAsHex(weiChatUserRequest.getPsw().getBytes()));
        int add = userInfoService.insertUserInfo(user);
        if (add > 0) {
            return AjaxResult.success("注册成功！");
        } else {
            return AjaxResult.error("注册失败！");
        }
    }

    /**
     * 用户登录
     * @param weiChatUserRequest
     * @return
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody WeiChatUserRequest weiChatUserRequest) {
        String md5Password = org.springframework.util.DigestUtils.md5DigestAsHex(weiChatUserRequest.getPsw().getBytes());
        UserInfo user = userInfoService.hasLogin(weiChatUserRequest.getPhone(), md5Password);
        if (user == null) {
            return AjaxResult.error("账号或密码错误，请重新输入！");
        }
        user.setStatus(1);
        int update = userInfoService.updateUserInfo(user);
        if (update > 0) {
            return AjaxResult.success(user);
        } else {
            return AjaxResult.error("登录失败");
        }
    }

    /**
     * 退出登录
     * @param weiChatUserRequest
     * @return
     */
    @PostMapping("/loginOut")
    public AjaxResult loginOut(@RequestBody WeiChatUserRequest weiChatUserRequest) {
        UserInfo user = userInfoService.getUserByPhone(weiChatUserRequest.getPhone());
        if (user == null) {
            return AjaxResult.error("用户不存在！");
        }
        user.setStatus(0);
        int update = userInfoService.updateUserInfo(user);
        if (update > 0) {
            return AjaxResult.success("退出登录成功！");
        } else {
            return AjaxResult.error("退出登录失败！");
        }
    }

    /**
     * 忘记密码
     * @param weiChatUserRequest
     * @param sessionId
     * @return
     */
    @PostMapping("/forgetPwd")
    public AjaxResult forgetPwd(@RequestBody WeiChatUserRequest weiChatUserRequest, @RequestHeader(value = "SESSIONID") String sessionId) {
        String code = redisUtil.get("sms_code:" + sessionId);
        if (StringUtils.isBlank(code)) {
            return AjaxResult.error("验证码已失效！");
        }
        if (weiChatUserRequest.getCode() == null) {
            return AjaxResult.error("请输入验证码！");
        }
        if (weiChatUserRequest.getPhone() == null) {
            return AjaxResult.error("请输入手机号！");
        }
        if (weiChatUserRequest.getPsw() == null) {
            return AjaxResult.error("请输入密码！");
        }
        if (!weiChatUserRequest.getCode().equals(code)) {
            return AjaxResult.error("验证码错误！");
        }

        UserInfo user = userInfoService.getUserByPhone(weiChatUserRequest.getPhone());
        if (user == null) {
            return AjaxResult.error("账号不存在！");
        }
        user.setPassword(DigestUtils.md5DigestAsHex(weiChatUserRequest.getPsw().getBytes()));
        user.setStatus(0);
        int update = userInfoService.updateUserInfo(user);
        if (update > 0) {
            return AjaxResult.success("密码修改成功！");
        } else {
            return AjaxResult.error("密码修改失败！");
        }
    }

}
